package com.example.recyclerviewtest;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;

import java.util.HashMap;
import java.util.List;

public class RecAdapter extends RecyclerView.Adapter<RecAdapter.Ra> {
    private List<TestBeam> testBeams;
    private HashMap<String,Integer> indexMap = new HashMap<>();

    @NonNull
    @Override
    public Ra onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new Ra(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_classify,parent,false));
    }

    @Override
    public void onBindViewHolder(@NonNull Ra holder, int position) {
        TestBeam testBeam = testBeams.get(position);
        holder.textView.setText(testBeam.getName());
    }

    public void setList(List<TestBeam> testBeams){
        this.testBeams = testBeams;
        final HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.UPPERCASE);
        for (int i=0;i<testBeams.size();i++){
            try{
                String[] args = PinyinHelper.toHanyuPinyinStringArray(testBeams.get(i).getName().charAt(0), format);
                //获取文字的第一个拼音
                String pinyin = String.valueOf(args[0].charAt(0));
                //保存第一条字母的索引位置，目的是后面可以快速跳转到对应的位置
                if (indexMap.get(pinyin) == null){
                    indexMap.put(pinyin,i);
                }else {
                    continue;
                }
            }catch (Exception e){
                Log.e("日志","在第"+i+"个字符时转换失败,原因："+e.getLocalizedMessage());
            }
        }
        notifyDataSetChanged();
    }

    public HashMap<String,Integer> getIndexMap(){
        return indexMap;
    }

    @Override
    public int getItemCount() {
        if (testBeams == null){
            return 0;
        }
        return testBeams.size();
    }


    public class Ra extends RecyclerView.ViewHolder {
        private TextView textView;
        public Ra(@NonNull View itemView) {
            super(itemView);
            textView = itemView.findViewById(R.id.test);
        }
    }
}
